<template>
  <basic-container>
    <avue-crud
      :option="option"
      :search.sync="search"
      :table-loading="loading"
      :data="data"
      :page.sync="page"
      :permission="permissionList"
      :before-open="beforeOpen"
      v-model="form"
      ref="crud"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @sort-change="sortChange"
      @row-save="rowSave"
      @on-load="onLoad"
    >
      <template slot-scope="scope" slot="menu">
        <el-button
          icon="el-icon-view"
          size="small"
          type="text"
          v-if="permission.activity_view"
          @click.stop="handleView(scope.row, scope.index)"
          >查 看</el-button
        >
        <el-button
          icon="el-icon-edit"
          size="small"
          type="text"
          v-if="permission.activity_add"
          @click.stop="handleEdit(scope.row, scope.index)"
          >编 辑</el-button
        >
      </template>
      <template slot="menuLeft">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="small"
          v-if="permission.activity_add"
          @click.stop="handleSave"
          >新 增</el-button
        >
        <!-- <el-button
          type="danger"
          size="small"
          icon="el-icon-delete"
          plain
          v-if="permission.service_info_delete"
          @click="handleDelete"
          >删 除
        </el-button> -->
      </template>
    </avue-crud>
    <el-dialog
      class="avue-dialog"
      :title="dialogText + '活动'"
      append-to-body
      :close-on-click-modal="false"
      :visible.sync="dialogVisible"
      :before-close="handleClose"
    >
      <activitydeposit-form
        :inputForm="activitydepositForm"
        :method="dialogType"
        ref="toActivitydepositForm"
      />
      <span slot="footer" class="dialog-footer" v-if="dialogType != 'view'">
        <el-button size="small" @click="handleSubmit" v-preventClick
          >提交</el-button
        >
      </span>
    </el-dialog>
    <el-dialog
      title="数据导入"
      append-to-body
      :visible.sync="excelBox"
      width="555px"
    >
      <avue-form
        :option="excelOption"
        v-model="excelForm"
        :upload-after="uploadAfter"
      >
        <template slot="excelTemplate">
          <el-button type="primary" @click="handleTemplate">
            点击下载<i class="el-icon-download el-icon--right"></i>
          </el-button>
        </template>
      </avue-form>
    </el-dialog>
  </basic-container>
</template>

<script>
import {
  getList,
  add,
  getDetail,
} from "@/api/rb-oem/activity/activity_deposit";
import { mapGetters } from "vuex";
import { dateFormat } from "@/util/date";
import { downloadFileExcel } from "@/util/util";
import selectPage from "@/components/select-page/select-page";
import activitydepositForm from "./form/activitydeposit_form";

export default {
  components: {
    selectPage,
    activitydepositForm,
  },
  data() {
    return {
      form: {},
      query: {},
      search: {},
      loading: false,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
      },
      selectionList: [],
      option: {
        height: "calc(50vh - 50px)",
        calcHeight: 30,
        tip: false,
        border: true,
        index: true,
        viewBtn: false,
        addBtn: false,
        editBtn: false,
        delBtn: false,
        selection: true,
        searchMenuSpan: 24,
        columnBtn: false,
        labelWidth: 120, //弹出表单的标题的统一宽度
        searchLabelWidth: 120, //搜索框标题宽度
        menuWidth: 220, //操作栏宽度
        emptyBtnText: "重置",
        column: [
          {
            label: "套餐编号",
            prop: "mealCode",
            type: "input",
            overHidden: true,
          },
          {
            label: "套餐名称",
            prop: "mealName",
            type: "input",
            overHidden: true,
            search: true,
          },
          {
            label: "优先级",
            prop: "sortNo",
            type: "input",
            overHidden: true,
          },
          {
            label: "套餐类型",
            prop: "mealType",
            type: "select",
            dicUrl: "/api/blade-system/dict/dictionary?code=pledge_meal_type",
            props: {
              label: "dictValue",
              value: "dictKey",
            },
            dataType: "string",
            showColumn: false,
            search: true,
            rules: [
              {
                required: true,
                message: "请输入套餐类型",
                trigger: "blur",
              },
            ],
          },
          {
            label: "套餐状态",
            prop: "isEnable",
            type: "select",
            dicUrl: "/api/blade-system/dict/dictionary?code=pledge_is_enable",
            props: {
              label: "dictValue",
              value: "dictKey",
            },
            dataType: "string",
            showColumn: false,
            search: true,
            rules: [
              {
                required: true,
                message: "请输入套餐状态",
                trigger: "blur",
              },
            ],
          },
          {
            label: "活动类型",
            prop: "mealActiveType",
            type: "select",
            dicUrl:
              "/api/blade-system/dict/dictionary?code=pledge_meal_active_type",
            props: {
              label: "dictValue",
              value: "dictKey",
            },
            dataType: "string",
            showColumn: false,
            search: true,
            rules: [
              {
                required: true,
                message: "请输入活动类型",
                trigger: "blur",
              },
            ],
          },
          {
            label: '商品大图',
            prop: 'logo',
            type: 'upload',
            listType: 'picture-img',
            action: '/api/blade-resource/oss/endpoint/put-file-public',
            loadText: '图片上传中，请稍等',
            limit: 1,
            fileSize: 10240,
            span: 24,
            propsHttp: {
              res: 'data',
              url: 'link'
            },
            tip: '只能上传jpg/png文件，且不且不超过10Mb',
            showColumn: false,
          },
        ],
      },
      data: [],
      excelBox: false,
      excelForm: {},
      excelOption: {
        submitBtn: false,
        emptyBtn: false,
        column: [
          {
            label: "模板上传",
            prop: "excelFile",
            type: "upload",
            drag: true,
            loadText: "模板上传中，请稍等",
            span: 24,
            propsHttp: {
              res: "data",
            },
            tip: "请上传 .xls,.xlsx 标准格式文件",
            action: "/api/rb-oem/oem/active/activerecord/importDebt",
          },
          {
            label: "模板下载",
            prop: "excelTemplate",
            formslot: true,
            span: 24,
          },
        ],
      },
      dialogVisible: false,
      dialogType: "", //打开类型 add/edit
      dialogText: "",
      activitydepositForm: {
        beginDate: "",
        content: "",
        endDate: "",
        hasChild: "0",
        id: "",
        ifRefund: 0,
        ifRefundAmt: 0,
        ifReturn: 0,
        ifReturnAmt: 0,
        setServiceCharge: 0,
        isEnable: '1',
        logo: "",
        mealActiveType: '',
        mealCode: "",
        mealName: "",
        mealType: '',
        merchantActiveCode: "",
        orgActiveCode: "",
        productList: [],
        serviceActiveCode: "",
        serviceAssessCode: "",
        // serviceNo: "",
        sortNo: '',
        timeDate: []
      },
    };
  },
  computed: {
    ...mapGetters(["permission"]),
    permissionList() {
      return {
        // addBtn: this.vaildData(this.permission.trade_add, false),
        viewBtn: this.vaildData(this.permission.active_debt_view, false),
        // delBtn: this.vaildData(this.permission.trade_delete, false),
        // editBtn: this.vaildData(this.permission.trade_edit, false),
        exportBtn: this.vaildData(this.permission.active_debt_export, false),
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(",");
    },
    // 交易状态
    rptPayStateType() {
      return (row) => {
        if (row.rptPayState == 0) {
          return "#E6A23C"; //未支付
        } else if (row.rptPayState == 1 && row.rptIsRefund !== 0) {
          return "#6463bf"; //支付成功（已退款）
        } else if (row.rptPayState == 1) {
          return "#67C23A"; //支付成功
        } else if (row.rptPayState == 2) {
          return "#909399"; //支付失败
        } else if (row.rptPayState == 3) {
          return "#909399"; //取消支付
        } else if (row.rptPayState == 4) {
          return "#909399"; //退款中
        } else if (row.rptPayState == 5) {
          return "#2fdeebf2"; //已退款
        } else if (row.rptPayState == 6) {
          return "#909399"; //退款失败
        } else {
          return "#909399";
        }
      };
    },
    exhibition() {
      return (val) => {
        if (val == "" || val == "-1") {
          return (val = 0);
        } else {
          return val;
        }
      };
    },
  },
  watch: {},
  created() {
    // this.getServiceInfoSimpleList({isSelectChild:0})
  },
  methods: {
    handleSubmit() {
      if (this.dialogType === "add") {
        this.$refs["toActivitydepositForm"].$refs["inputForm"].validate((valid) => {
          if (valid) {
            if (this.activitydepositForm.serviceNo) {
              this.activitydepositForm.serviceNo = this.activitydepositForm.serviceNo.join(",");
            }
            add(this.activitydepositForm).then(
              (res) => {
                this.dialogVisible = false;
                this.searchReset();
                if (res.data.code == "200") {
                  this.$message({
                    type: "success",
                    message: "操作成功!",
                  });
                } else {
                  this.$message({
                    type: "error",
                    message: res.data.message,
                  });
                }
              },
              (error) => {
                window.console.log(error);
              }
            );
          } else {
            return false;
          }
        });
      } else if (this.dialogType === "edit") {
        this.$refs["toActivitydepositForm"].$refs["inputForm"].validate((valid) => {
          if (valid) {
            if (this.activitydepositForm.serviceNo) {
              this.activitydepositForm.serviceNo = this.activitydepositForm.serviceNo.join(",");
            }
            add(this.activitydepositForm).then(
              (res) => {
                this.dialogVisible = false;
                this.searchReset();
                if (res.data.code == "200") {
                  this.$message({
                    type: "success",
                    message: "操作成功!",
                  });
                } else {
                  this.$message({
                    type: "error",
                    message: res.data.message,
                  });
                }
              },
              (error) => {
                window.console.log(error);
              }
            );
          } else {
            return false;
          }
        });
      }
    },
    /**
     * @func 新增
     * @desc 点击新增初始化显示基本信息
     * */
    handleSave() {
      this.dialogVisible = true;
      this.dialogType = "add";
      this.dialogText = "新增";
      this.activitydepositForm.id = null;
    },
    /**
     * @func 编辑
     * @desc 点击编辑回显基本信息
     * @param {Object} row - 表格绑定的信息
     * */
    handleEdit(row) {
      this.dialogVisible = true;
      this.dialogType = "edit";
      this.dialogText = "编辑";
      getDetail({ mealCode: row.mealCode }).then((res) => {
        const data = res.data.data;
        // this.activitydepositForm = data;
        data.mealType = data.mealType.toString();
        data.mealActiveType = data.mealActiveType.toString();
        data.isEnable = data.isEnable.toString();
        if (data.beginDate && data.endDate) {
            this.$set(data, 'timeDate', [data.beginDate, data.endDate])
        }
        if (data.logo) {
            this.$refs["toActivitydepositForm"].logoFileList = []
            this.$refs["toActivitydepositForm"].logoFileList.push({url: data.logo})
        }
        this.$nextTick(() => {
          this.activitydepositForm = data;
        });
      });
    },
    handleView(row) {
      this.dialogVisible = true;
      this.dialogType = "view";
      this.dialogText = "查看";
      getDetail({ mealCode: row.mealCode }).then((res) => {
        const data = res.data.data;
        // this.activitydepositForm = data;
        data.mealType = data.mealType.toString();
        data.mealActiveType = data.mealActiveType.toString();
        data.isEnable = data.isEnable.toString();
        if (data.beginDate && data.endDate) {
            this.$set(data, 'timeDate', [data.beginDate, data.endDate])
        }
        if (data.logo) {
            this.$refs["toActivitydepositForm"].logoFileList = []
            this.$refs["toActivitydepositForm"].logoFileList.push({url: data.logo})
        }
        this.$nextTick(() => {
          this.activitydepositForm = data;
        });
      });
    },
    /**
     * @func 关闭弹窗
     * @desc 点击关闭的回调
     * @param {Function} done - 完成的回调
     * */
    handleClose(done) {
      this.$refs["toActivitydepositForm"].logoFileList = []
      this.activitydepositForm.productList = []
      this.$refs["toActivitydepositForm"].$refs["inputForm"].resetFields();
      this.onLoad(this.page, this.query);
      done();
    },
    /**
     * @func edit,view 打开之前回调
     * @desc 点击获取点击天数时间
     * */
    beforeOpen(done, type) {
      if (["edit", "view"].includes(type)) {
        // getDetail(this.form.id).then(res => {
        //   this.form = res.data.data;
        // });
      }
      done();
    },
    /**
     * @func 重置
     * @desc 重置查询条件
     * */
    searchReset() {
      this.query = {};
      this.search = {};
      this.onLoad(this.page);
    },
    /**
     * @func 搜索
     * @desc 根据条件查询
     * @param {params} params --- 条件查询
     * */
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    /**
     * @func 选中单元格
     * @desc 选中单元格数据
     * @param {list} list --- 选中单元格数据-数组
     * */
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    /**
     * @func 分页页码
     * @desc 分页页码改变时会触发
     * */
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
      // this.refreshChange();
    },
    /**
     * @func 当前页个数
     * @desc pageSize改变时会触发
     * */
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
      // this.refreshChange();
    },
    /**
     * @func 刷新
     * @desc 点击刷新按钮触发该事件
     * */
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    rowSave(row, done, loading) {
      add(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          done();
        },
        (error) => {
          loading();
          window.console.log(error);
        }
      );
    },
    /**
     * @func 初始化
     * @desc 表格初始化查询数据
     * */
    onLoad(page, params = {}) {
      this.loading = true;
      // if(this.query.isSelectChildArr){
      //   this.query.isSelectChild = this.query.isSelectChildArr[0];
      // }
      getList(
        page.currentPage,
        page.pageSize,
        Object.assign(params, this.query)
      ).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },
    handleImport() {
      this.excelBox = true;
    },
    /**
     * @func 导出
     * @desc 根据条件导出
     * */
    handleExport() {
      let params = {
        ...this.search,
        current: "-1",
        size: "-1",
      };

      this.$confirm("是否导出用户数据?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        getExport(this.query).then(
          (res) => {
            // downloadFileExcel(res);
            this.$message({
              type: "success",
              message: res.data.msg,
            });
          },
          (error) => {
            window.console.log(error);
          }
        );
      });
    },

    /**
     * @func 排序
     * @desc 根据表格字段排序
     * */
    sortChange(val) {
      if (val.order == "ascending") {
        //正序
        this.query.ascs = val.prop;
        this.query.descs = "";
      } else {
        //倒序
        this.query.descs = val.prop;
        this.query.ascs = "";
      }
      this.refreshChange();
    },
    uploadAfter(res, done) {
      this.excelBox = false;
      this.refreshChange();
      done();
    },
    handleTemplate() {
      getExportTemplate().then(
        (res) => {
          downloadFileExcel(res);
        },
        (error) => {
          window.console.log(error);
        }
      );
    },
  },
};
</script>

<style lang="scss" scoped>
/deep/ .el-tag--dark.el-tag--success {
  border: none !important;
}
</style>